//
// AWS Manager - A free AWS console application demonstrating advanced concepts
// Copyright (C) 2008-2010 Sean O'Dell. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.awsmanager.common;

import com.awsmanager.utils.ProcessException;
import com.sun.data.provider.RowKey;
import com.sun.data.provider.impl.ObjectListDataProvider;
import com.xerox.amazonws.ec2.EC2Exception;
import com.xerox.amazonws.ec2.GroupDescription.IpPermission;
import com.xerox.amazonws.ec2.Jec2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Sean ODell
 */
public class EC2IpPermissionDataProvider extends ObjectListDataProvider {

    private ArrayList ec2IpPermissionList = new ArrayList();

    public EC2IpPermissionDataProvider() {
        setList(ec2IpPermissionList);
        setObjectType(EC2IpPermission.class);
    }

    public void load(Map ec2IpPermissionsInfo,
            EC2SecurityGroupDataProvider ec2SecurityGroupDataProvider) {

        ArrayList rowKeysList = (ArrayList) ec2IpPermissionsInfo.get("rowKeys");
        List<String> cidrIps = null;
        clearObjectList();

        if (ec2SecurityGroupDataProvider == null) {
            return;
        }

        for (int i = 0; i < rowKeysList.size(); i++) {

            EC2SecurityGroup securityGroup = ec2SecurityGroupDataProvider.getSecurityGroup(
                    (RowKey) rowKeysList.get(i));

            List<IpPermission> ipPermissions = securityGroup.getpermissions();

            for (IpPermission ipPermission : ipPermissions) {
                EC2IpPermission ipPermissionInfo = new EC2IpPermission();
                ipPermissionInfo.setSecurityGroupRegion(securityGroup.getRegion());
                ipPermissionInfo.setsecurityGroupName(securityGroup.getName());
                ipPermissionInfo.setProtocol(ipPermission.getProtocol());
                ipPermissionInfo.setFromPort(ipPermission.getFromPort());
                ipPermissionInfo.setToPort(ipPermission.getToPort());
                cidrIps = ipPermission.getIpRanges();
                if (cidrIps != null) {
                    for (String cidrIp : cidrIps) {
                        if (cidrIp != null) {
                            EC2IpPermission ipPermissionInfoCopy = ipPermissionInfo.copy();
                            ipPermissionInfoCopy.setcidrIp(cidrIp);
                            getList().add(ipPermissionInfoCopy);
                        }
                    }
                } else {
                    getList().add(ipPermissionInfo);
                }
            }
        }
    }

    public EC2IpPermission getIpPermission(RowKey rowKey) {
        EC2IpPermission ec2IpPermission = (EC2IpPermission) getObject(rowKey);
        return ec2IpPermission;
    }

    public Map addIpPermissionExternal(
            EC2Connection ec2connection,
            Map ec2IpPermissionsInfo) {

        Map statusMsg = new HashMap();
        ProcessException processException = new ProcessException();

        if (ec2connection == null) {
            statusMsg.put("type", "warning");
            statusMsg.put("msg", "Connection to EC2 timed out. Please re-load user settings.");
            return statusMsg;
        } else {
            if(ec2connection.getEc2RegionInfo() == null) {
            statusMsg.put("type", "warning");
            statusMsg.put("msg", "Connection to EC2 timed out. Please re-load user settings.");
            return statusMsg;
            }
        }

        EC2Region ec2RegionInfo = null;
        ec2RegionInfo = (EC2Region) ec2connection.getEc2RegionInfo().get((String) ec2IpPermissionsInfo.get("securityregion"));

        try {
            ec2RegionInfo.getRegionConnection().authorizeSecurityGroupIngress(
                    (String) ec2IpPermissionsInfo.get("securitygroup"),
                    (String) ec2IpPermissionsInfo.get("protocol"),
                    Integer.parseInt((String) ec2IpPermissionsInfo.get("fromPort")),
                    Integer.parseInt((String) ec2IpPermissionsInfo.get("toPort")),
                    (String) ec2IpPermissionsInfo.get("cidrip"));
            statusMsg.put("type", "success");
            statusMsg.put("msg", "IP Permission granted.");
        } catch (EC2Exception ex) {
            Logger.getLogger(EC2IpPermissionDataProvider.class.getName()).log(Level.SEVERE, null, "|" + ex.toString() + "|");
            statusMsg.put("type", "error");
            statusMsg.put("msg", processException.extractExMsg(ex));
        }

        return statusMsg;
    }

    public String revokeIpPermissionExternal(
            EC2Connection ec2connection,
            RowKey[] selectedRowKeys) {

        String statusMsg = new String();
        ProcessException processException = new ProcessException();

        if (ec2connection == null) {
            statusMsg = "Connection to EC2 timed out. Please re-load user settings.";
            return statusMsg;
        }

        statusMsg = statusMsg + "Deleted IP Permissions: \n\n";

        for (int i = 0; i < selectedRowKeys.length; i++) {
            RowKey rowKey = selectedRowKeys[i];
            EC2IpPermission ec2IpPermission = getIpPermission(rowKey);
            EC2Region ec2RegionInfo = null;
            ec2RegionInfo = (EC2Region) ec2connection.getEc2RegionInfo().get(ec2IpPermission.getSecurityGroupRegion());

            try {
                ec2RegionInfo.getRegionConnection().revokeSecurityGroupIngress(
                        ec2IpPermission.getsecurityGroupName(),
                        ec2IpPermission.getProtocol(),
                        ec2IpPermission.getFromPort(),
                        ec2IpPermission.getToPort(),
                        ec2IpPermission.getcidrIp());

                statusMsg = statusMsg +
                        "Security Group: " + ec2IpPermission.getSecurityGroupRegion() +
                        ", " + ec2IpPermission.getsecurityGroupName() +
                        ", " + ec2IpPermission.getProtocol() +
                        ", " + ec2IpPermission.getFromPort() +
                        ", " + ec2IpPermission.getToPort() +
                        ", " + ec2IpPermission.getcidrIp() +
                        "\n";

            } catch (EC2Exception ex) {
                Logger.getLogger(EC2IpPermissionDataProvider.class.getName()).log(Level.SEVERE, null, ex.toString());
                statusMsg = processException.extractExMsg(ex);
            }

        }
        return statusMsg;
    }
}